<template>
  <div class="product-detail-container">
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else>
      <div class="main-info">
        <img :src="product.mainImage" class="main-img" alt="商品主图" />
        <div class="info-block">
          <h2 class="product-name">{{ product.name }}</h2>
          <div class="product-price">￥{{ product.price }}</div>
          <div class="meta">
            <span>库存：{{ product.stock }}</span>
            <span>销量：{{ product.sales }}</span>
          </div>
          <div class="meta">
            <span>分类：{{ product.categoryName }}</span>
            <span>卖家：{{ product.sellerName }}</span>
          </div>
          <div class="meta">
            <span>状态：
              <span v-if="product.status === 1">在售</span>
              <span v-else-if="product.status === 0">下架</span>
              <span v-else>未知</span>
            </span>
          </div>
          <div class="btn-group">
            <el-button type="primary" :disabled="!canBuy" @click="handleBuy">立即购买</el-button>
            <el-button type="primary" @click="handleAddCart">加入购物车</el-button>
            <el-button @click="goBack">返回上一页</el-button>
            <el-button @click="goHome" link>回到首页</el-button>
          </div>
          <div v-if="!canBuy" class="status-tip">
            <span v-if="product.status === 0">该商品已下架，无法购买</span>
            <span v-else-if="product.stock === 0">该商品已售罄</span>
          </div>
        </div>
      </div>
      <div class="desc-block">
        <h3>商品介绍</h3>
        <div class="desc">{{ product.description }}</div>
      </div>
    </div>
  </div>
  <el-dialog v-model="showOrderDialog" title="确认订单" width="400px">
    <div v-if="addressList.length">
      <el-form>
        <el-form-item label="收货地址">
          <el-select v-model="selectedAddressId" placeholder="请选择收货地址" style="width: 100%;">
            <el-option
              v-for="addr in addressList"
              :key="addr.addressId"
              :label="`${addr.receiverName} ${addr.phone} ${addr.province}${addr.city}${addr.district}${addr.detailAddress}`"
              :value="addr.addressId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="购买数量">
          <el-input-number v-model="buyQuantity" :min="1" :max="product.stock" />
        </el-form-item>
      </el-form>
    </div>
    <div v-else style="color: #bbb;">请先添加收货地址</div>
    <template #footer>
      <el-button @click="showOrderDialog = false">取消</el-button>
      <el-button type="primary" @click="submitOrder" :disabled="!selectedAddressId">提交订单</el-button>
    </template>
  </el-dialog>
</template>


<script setup>
import { useRoute, useRouter } from 'vue-router';
import request, { getUserAddresses } from '@/utils/request';
import { useUserStore } from '@/stores/userStore';
import { ElMessage } from 'element-plus';
import { ref, onMounted, computed } from 'vue';
import { useCartStore } from '@/stores/cartStore'

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const cartStore = useCartStore()

const product = ref({});
const loading = ref(true);
const error = ref('');

const canBuy = computed(() => product.value.status === 1 && product.value.stock > 0);

// 新增：下单弹窗相关变量
const showOrderDialog = ref(false)
const addressList = ref([])
const selectedAddressId = ref(null)
const buyQuantity = ref(1)

const fetchDetail = async () => {
  loading.value = true;
  error.value = '';
  try {
    const res = await request.get(`/api/products/${route.params.id}`);
    if (!res || !res.productId) {
      error.value = '商品不存在';
    } else {
      product.value = res;
    }
  } catch (e) {
    if (e.response && e.response.status === 404) {
      error.value = '商品不存在';
    } else {
      error.value = '加载失败，请稍后重试';
    }
  } finally {
    loading.value = false;
  }
};

// 修改handleBuy，弹窗选地址和数量
const handleBuy = async () => {
  if (!userStore.isAuthenticated) {
    router.push({ name: 'Login', query: { redirect: router.currentRoute.value.fullPath } });
    return;
  }
  try {
    const res = await getUserAddresses();
    if (res.success && res.data && res.data.length) {
      addressList.value = res.data;
      selectedAddressId.value = res.data.find(a => a.isDefault === 1)?.addressId || res.data[0].addressId;
      buyQuantity.value = 1;
      showOrderDialog.value = true;
    } else {
      ElMessage.error('请先添加收货地址');
    }
  } catch {
    ElMessage.error('获取地址失败');
  }
};

// 新增：提交订单
const submitOrder = async () => {
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择收货地址');
    return;
  }
  if (buyQuantity.value < 1) {
    ElMessage.warning('购买数量不能小于1');
    return;
  }
  try {
    const res = await request.post('/api/order/create', {
      addressId: selectedAddressId.value,
      items: [{ productId: product.value.productId, quantity: buyQuantity.value }]
    });
    if (res.success && res.data) {
      ElMessage.success('下单成功');
      showOrderDialog.value = false;
      router.push(`/profile/orders/${res.data.orderId}`);
    } else {
      ElMessage.error(res.message || '下单失败');
    }
  } catch (e) {
    ElMessage.error(e.response?.data?.message || '下单失败');
  }
};

const handleAddCart = async () => {
  if (product.value.status !== 1) {
    ElMessage.warning('商品未上架');
    return;
  }
  if (product.value.stock <= 0) {
    ElMessage.warning('库存不足');
    return;
  }
  if (!userStore.isAuthenticated) {
    ElMessage.warning('请先登录');
    router.push({ name: 'Login', query: { redirect: router.currentRoute.value.fullPath } });
    return;
  }
  try {
    await cartStore.addToCart(product.value.productId, 1);
    ElMessage.success('已加入购物车');
  } catch (e) {
    ElMessage.error('加入购物车失败');
  }
};

const goBack = () => {
  router.back();
};
const goHome = () => {
  router.push('/');
};

onMounted(() => {
  fetchDetail();
});
</script>

<style scoped>
.product-detail-container {
  max-width: 900px;
  margin: 40px auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 16px rgba(0,0,0,0.06);
  padding: 32px 32px 24px 32px;
}
.loading, .error {
  text-align: center;
  font-size: 20px;
  color: #888;
  margin: 60px 0;
}
.main-info {
  display: flex;
  gap: 32px;
}
.main-img {
  width: 320px;
  height: 320px;
  object-fit: cover;
  border-radius: 12px;
  background: #f5f5f5;
}
.info-block {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.product-name {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
}
.product-price {
  font-size: 26px;
  color: #e53935;
  font-weight: bold;
  margin-bottom: 8px;
}
.meta {
  color: #666;
  font-size: 16px;
  margin-bottom: 4px;
  display: flex;
  gap: 24px;
}
.btn-group {
  margin-top: 18px;
  display: flex;
  gap: 16px;
}
.status-tip {
  color: #e53935;
  font-size: 16px;
  margin-top: 8px;
}
.desc-block {
  margin-top: 36px;
}
.desc-block h3 {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 12px;
}
.desc {
  color: #444;
  font-size: 16px;
  line-height: 1.8;
  background: #f8fafc;
  border-radius: 8px;
  padding: 18px 16px;
}
</style> 